<?php
/**
 * Created by PhpStorm.
 * User: alexey
 * Date: 7/29/14
 * Time: 8:59 PM
 */

namespace util;

use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

include_once("BrowserLogger.php");

class ImageUtil
{

  private static $logger;

  static function getLogger()
  {
    if (self::$logger == null) {
      self::$logger = new BrowserLogger();
    }
    return self::$logger;
  }

  static function createImagePreview($pathToImage, $newWidth, $outputDir, $filesDir)
  {

    $outputDir .= DIRECTORY_SEPARATOR . self::getPathRelativeTo($pathToImage, $filesDir) . DIRECTORY_SEPARATOR;

    if (!file_exists($outputDir)) {
      mkdir($outputDir, 0777, true);
    }

    $targetPath = $outputDir . self::getImagePath($pathToImage);
    $size = getimagesize($pathToImage);
    $scale = $size[0] / $newWidth;
    $countedHeight = $size[1] / $scale;
    $source = self::createImageByType($pathToImage);
    $target = imagecreatetruecolor($newWidth, $countedHeight);

    imagecopyresampled(
      $target,
      $source,
      0, 0,
      0, 0,
      $newWidth,
      $countedHeight,
      $size[0],
      $size[1]
    );

    imagejpeg($target, $targetPath, 100);

    imagedestroy($target);
    imagedestroy($source);
  }

  static function getImageType($imgBaseName)
  {
    return pathinfo($imgBaseName, PATHINFO_EXTENSION);
  }

  static function createImageByType($pathToImage)
  {
    $type = self::getImageType($pathToImage);
    switch (strtolower($type)) {
      case "jpg":
        return imagecreatefromjpeg($pathToImage);
      case "jpeg":
        return imagecreatefromjpeg($pathToImage);
      case "png":
        return imagecreatefrompng($pathToImage);
      case "gif":
        return imagecreatefromgif($pathToImage);
      default:
        return imagecreatefromjpeg($pathToImage);
    }
  }

  static function getPathRelativeTo($path, $relative)
  {
    $pos = strpos($path, $relative) + strlen($relative);
    if ($pos > 0) {
      $result = substr($path, $pos);
      if (strpos($result, ".")) {
        $result = str_replace(basename($result), "", $result);
        return $result;
      }
    } else {
      return "";
    }
  }

  static function getImagePath($pathToImage)
  {
    return basename($pathToImage);
  }

  static function getAllFilesFromDir($dirForScan)
  {

    $objects = new RecursiveIteratorIterator(
      new RecursiveDirectoryIterator($dirForScan),
      RecursiveIteratorIterator::SELF_FIRST);
    return $objects;
  }

  static function createAllFilesPreview($filesDir, $outputDir, $width)
  {
    $files = self::getAllFilesFromDir($filesDir);
    foreach ($files as $key => $value) {
      self::getLogger()->info("Creating preview of image: " . $value);
      self::createImagePreview($value, $width, $outputDir, $filesDir);
    }
  }

} 